<template>
  <el-breadcrumb
    separator="/"
    class="mb-1"
    :class="{ 'mx-15': useLocale.isMob }"
    style="vertical-align: bottom"
  >
    <el-breadcrumb-item>
      <div class="flex align-center">
        <el-icon :size="18"><Setting /></el-icon>
        <span class="pl">设定</span>
      </div>
    </el-breadcrumb-item>
    <el-breadcrumb-item>默認回復設定</el-breadcrumb-item>
    <el-breadcrumb-item>人工回复</el-breadcrumb-item>
  </el-breadcrumb>
  <div v-if="useLocale.isMob">
    <div class="mx-15 my-15 flex justify-between">
      <el-space :size="10">
        <el-button type="primary" size="small" plain round @click="batchBlack"
          >设置黑名单</el-button
        >
        <el-button
          type="primary"
          size="small"
          plain
          round
          @click="openBatchStatus"
          >标记状态</el-button
        >
        <el-button
          type="primary"
          size="small"
          plain
          round
          @click="batchUsersGroup"
          >设置分组</el-button
        >
      </el-space>
      <el-button
        :icon="Search"
        size="small"
        circle
        @click="
          () => {
            mobFilter = true;
          }
        "
      />
    </div>

    <div class="mob-list mt-2">
      <el-scrollbar ref="scrollbarRef" class="scroll">
        <div
          class="mob-list-item text-content-color font"
          v-for="(item, index) in tableData"
        >
          <div class="flex align-center mb-1">
            <el-checkbox
              v-model="item.checked"
              @change="(value) => mobChecked(value, item)"
            />
            <el-avatar
              class="ml-1"
              shape="circle"
              :size="60"
              fit="fill"
              :src="item.user_img"
            />
            <div class="flex-1 ml-15">
              <div class="flex justify-between">
                <span class="font-mder text-main-color">{{
                  item.fb_name
                }}</span>
                <span class="primaryColor">{{ item.status_name }}</span>
              </div>
              <div class="mt font-sm">{{ item.msg_user_id }}</div>
            </div>
          </div>
          <div class="flex justify-between border-bottom py-15">
            <div style="width: 70px">讯息内容</div>
            <span class="flex-1">{{ item.message }}</span>
          </div>
          <div class="flex justify-between border-bottom py-15">
            <span>时间</span>
            <span>{{ item.time }}</span>
          </div>

          <div wrap class="flex flex-wrap justify-end my-1">
            <el-button
              v-if="item.status_id != 2"
              class="mb-1"
              size="small"
              plain
              round
              @click="openStatus(index, item)"
              >标记状态</el-button
            >

            <el-button
              class="mb-1"
              size="small"
              plain
              round
              @click="openGroup(index, item)"
              >设置分组</el-button
            >
            <el-button
              class="mb-1"
              size="small"
              plain
              round
              type="primary"
              @click="dialogue(index, item)"
              >对话</el-button
            >
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div v-if="total > params.page_size" class="my-1 flex justify-center">
      <el-pagination
        v-model:current-page="params.current_page"
        v-model:page-size="params.page_size"
        :pager-count="5"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-card v-else class="box-card" shadow="hover">
    <div class="flex justify-between flex-wrap mb-2 mt">
      <el-space wrap :size="10" class="mt-1">
        <el-input
          v-model="params.keyword"
          style="width: 150px"
          placeholder="讯息内容"
        />
        <el-input
          v-model="params.fb_name"
          style="width: 150px"
          placeholder="用戶名稱"
        />

        <el-select v-model="params.status_id" style="width: 150px">
          <el-option
            v-for="item in filter.statusArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button :icon="Search" plain @click="search">查詢</el-button>
      </el-space>
      <el-space wrap :size="10" class="mt-1">
        <el-button type="primary" plain @click="batchBlack"
          >设置黑名单</el-button
        >
        <el-button type="primary" plain @click="openBatchStatus"
          >标记状态</el-button
        >
        <el-button type="primary" plain @click="batchUsersGroup"
          >设置分组</el-button
        >
      </el-space>
    </div>
    <el-table
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="头像" align="center" width="150">
        <template #default="scope">
          <el-image
            style="width: 100px"
            :src="scope.row.user_img"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="名称/PSID" align="center" width="200">
        <template #default="scope">
          <div class="flex flex-column align-center">
            <div>{{ scope.row.fb_name }}</div>
            <div class="mt">{{ scope.row.msg_user_id }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="message" label="讯息内容" />
      <el-table-column prop="status_name" label="状态" width="100" />
      <el-table-column prop="time" label="时间" width="120" />
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <div class="ec2-btncon">
            <el-button
              v-if="scope.row.status_id != 2"
              link
              size="small"
              type="info"
              @click="openStatus(scope.$index, scope.row)"
              >标记</el-button
            >
            <el-button
              link
              size="small"
              type="primary"
              @click="dialogue(scope.$index, scope.row)"
              >对话</el-button
            >
            <el-button
              link
              size="small"
              type="danger"
              @click="openGroup(scope.$index, scope.row)"
              >设置分组</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="total > params.page_size" class="mt-2 flex justify-center">
      <el-pagination
        v-model:current-page="params.current_page"
        v-model:page-size="params.page_size"
        :page-sizes="[20, 40, 60]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <set-group
    ref="groupRef"
    :row="currRow"
    :type="groupType"
    :euids="currEuids"
    :muti="groupMuti"
  ></set-group>
  <el-drawer v-model="mobFilter" size="80%">
    <template #header>
      <h4>筛选</h4>
    </template>
    <template #default>
      <el-space direction="vertical" fill style="width: 100%">
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">讯息内容</div>
          <el-input v-model="params.keyword" />
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">用戶名稱</div>
          <el-input v-model="params.fb_name" />
        </div>

        <div class="mb-1">
          <div class="font-sm text-tips-color mb">状态</div>
          <el-select v-model="params.status_id" style="width: 100%">
            <el-option
              v-for="item in filter.statusArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
      </el-space>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="mobClearFilter">清空</el-button>
        <el-button type="primary" @click="search">查询</el-button>
      </div>
    </template>
  </el-drawer>
  <el-dialog
    v-model="rel_status.visible"
    title="修改状态"
    :fullscreen="fit.fullscreen"
    :before-close="statusClose"
  >
    <el-radio-group v-model="rel_status.update_id">
      <template v-for="(item, index) in filter.statusArr" :key="index">
        <el-radio v-if="index !== 0" :value="item.id">{{ item.name }}</el-radio>
      </template>
    </el-radio-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="rel_status.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmStatus"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { nextTick, ref, onMounted, reactive, watch, computed } from "vue";
import { Search, Setting, ArrowDown } from "@element-plus/icons-vue";
import {
  $kfList,
  $kfStatus,
  $singleStatus,
  $batchStatus,
  $batchBlack,
} from "@api/setting";
import { $getGroup } from "@api/common";
import router from "@/router/";
import { useLocaleStore } from "@/store/locales";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const langkey = computed(() => useLocale.locale);
const useLocale = useLocaleStore();
const groupMuti = ref(false); //分组多选还是单选
const groupType = ref(""); //user users不同的axios
const groupRef = ref(); //组件名称
const scrollbarRef = ref(); //滚动条名称
const mobFilter = ref(false);
let currEuids = ref([]); //选择的行id
let currRow = ref(null); //选择行数据
let rel_status = reactive({
  visible: false,
  update_id: null,
  muti: [], //多选行状态
  mobMutiRow:[],//多行
  currType: "", //batch批量 //single单独
});
let params = ref({
  fb_name: "",
  status_id: "",
  keyword: "",
  current_page: 1,
  page_size: 10,
});
const filter = ref({
  statusArr: [],
});

const total = ref(0);
const tableData = ref([]);
let fit = reactive({
  fullscreen: false,
});

if (useLocale.isMob) {
  fit.fullscreen = true;
} else {
  fit.fullscreen = false;
}

onMounted(() => {
  getFilter();
});
const getFilter = async () => {
  const status_res = await $kfStatus();
  filter.value.statusArr = status_res.data.list;
  //初始化默认值
  params.value.status_id = status_res.data.list[0].id;

  getData();
};

const getData = async () => {
  currEuids.value = [];
  let res = await $kfList(params.value);
  if (res.code == 0) {
    if (useLocale.isMob) {
      res.data.table.forEach((ele) => {
        Reflect.set(ele, "checked", false);
      });
    }
    tableData.value = res.data.table;
    total.value = res.data.total;
    if (useLocale.isMob) {
      nextTick(() => {
        scrollbarRef.value.setScrollTop(0);
      });
    }
  }
};
const handleSizeChange = (val: number) => {
  params.value.page_size = val;
  getData();
};
const handleCurrentChange = (val: number) => {
  params.value.current_page = val;
  getData();
};
const handleSelectionChange = (val) => {
  currEuids.value = [];
  rel_status.muti=[];
  if (val.length !== 0) {
    val.forEach((ele) => {
      currEuids.value.push(ele.fb_user_id);
      rel_status.muti.push(ele.status_id);
    });
  }
  console.log(rel_status);
};
const search = () => {
  getData();
  mobFilter.value = false;
};
const openStatus = (index, row) => {
  rel_status.currType= "single";
  rel_status.update_id=row.status_id;
  currRow.value = row;
  rel_status.visible = true;
};
const openBatchStatus = () => {
  rel_status.currType = "batch";
  console.log(currEuids.value);
  console.log(rel_status.muti);
  if (currEuids.value.length == 0) {
    ElMessage({
      message: "请选择用户",
      type: "warning",
    });
    return false;
  }
  if(new Set(rel_status.muti).size!==1){
    ElMessage({
      message: "只能对相同状态的消息进行批量标记",
      type: "warning",
    });
    return false;
  }
  if(rel_status.muti[0]==2){
    ElMessage({
      message: "已处理的消息无法标记",
      type: "warning",
    });
    return false;
  }
  
 rel_status.visible = true;
};

const confirmStatus = async () => {
  let res = null;
  switch (rel_status.currType) {
    case "single":
      let arg = {
        fb_user_id: currRow.value.fb_user_id,
        status_id: rel_status.update_id,
      };
      console.log(arg);

      res = await $singleStatus(arg);

      break;
    case "batch":
      let args = {
        fb_user_ids: currEuids.value,
        status_id: rel_status.update_id,
      };
      console.log(args);
      res = await $batchStatus(args);
      break;
  }
  if (res.code == 0) {
    getData();
    ElMessage({
      message: "更新成功",
      type: "success",
    });
  } else {
    ElMessage.error(res.msg);
  }
  rel_status.visible = false;
};
const statusClose = (done: () => void) => {
  rel_status.muti= [];
  rel_status.update_id= null;
  done();
};
const openGroup = (index, row) => {
  groupMuti.value = true;
  groupType.value = "user";
  currRow.value = row;
  currEuids.value = [];
  groupRef.value.changeShow();
};

const batchUsersGroup = () => {
  if (currEuids.value.length == 0) {
    ElMessage({
      message: "请选择用户",
      type: "warning",
    });
    return false;
  }
  groupMuti.value = false;
  groupType.value = "users";
  currRow.value = {};
  groupRef.value.changeShow();
};
const batchBindUsers = async () => {
  if (currEuids.value.length !== 2) {
    ElMessage({
      message: "请选择2个用户进行关联",
      type: "warning",
    });
    return false;
  }
  ElMessageBox.confirm(
    "您確定要關聯選擇的兩個用戶嗎,關聯後信息會合併到一個用戶身份上並刪除另一個用戶信息?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      let res = await $bindUser({ euids: currEuids.value });
      if (res.code == 0) {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

const batchBlack = () => {
  if (currEuids.value.length == 0) {
    ElMessage({
      message: "请选择用户",
      type: "warning",
    });
    return false;
  }
  ElMessageBox.confirm("您确定要设置黑名单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await $batchBlack({ fb_user_ids: currEuids.value });
      if (res.code == 0) {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

const batchStatus = () => {
  if (currEuids.value.length == 0) {
    ElMessage({
      message: "请选择用户",
      type: "warning",
    });
    return false;
  }
  ElMessageBox.confirm("您确定要设置黑名单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await $batchStatus({ fb_user_ids: currEuids.value });
      if (res.code == 0) {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};



const dialogue = (index, row) => {
  console.log(row);
    router.push({
    path: "/setting/messageKf/dialog",
    query: {
      fb_user_id: row.fb_user_id,
      fb_account_id: row.fb_account_id,
      fb_name:row.fb_name
    },
  });
};


const mobClearFilter = () => {
  params.value.fb_name = "";
  params.value.keyword = "";
  params.value.status_id= filter.value.statusArr[0].id;
  params.value.current_page = 1;
  params.value.page_size = 10;
  getData();
};
const mobChecked = (v, item) => {
  rel_status.muti=[];
  if (v == true) {
    currEuids.value.push(item.fb_user_id);
    rel_status.mobMutiRow.push(item);
  } else {
    currEuids.value.splice(
      currEuids.value.findIndex((o) => o == item.fb_user_id),
      1
    );
     rel_status.mobMutiRow.splice(
      rel_status.mobMutiRow.findIndex((o) => o.fb_user_id == item.fb_user_id),
      1
    );
  }
  rel_status.mobMutiRow.forEach(ele=>{
    rel_status.muti.push(ele.status_id)
  })
  console.log(rel_status.muti);
};

watch(langkey, (newVal, oldVal) => {
  getFilter();
});
</script>
<style>
.ec2-btncon {
  .el-button {
    margin-bottom: 2px;
    justify-content: flex-start;
  }
  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>
<style lang="scss" scoped>
.mob-list {
  .mob-list-item {
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
  }
  .desc-item {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
  }
}
.scroll {
  height: calc(100vh - 220px);
}
.ec2-btncon {
  display: flex;
  flex-direction: column;
}
.primaryColor {
  color: var(--el-color-primary);
}
</style>
